package com.step.sprite.animation;

import java.util.ArrayList;

import com.step.Step;

public class Animation {
	protected int numFrames;
	protected ArrayList<KeyFrame> frames;
	protected int currentFrameIndex = 0;
	private boolean isPlaying = false;
	protected float interpolation;
	protected float fps = 70;	
	private String currentFrameName;
	private int loopStartIndex;
	private boolean loop = true;
	protected KeyFrame currentFrame;
	
	public Animation(KeyFrame...frames){
		this.frames = new ArrayList<KeyFrame>();
		setFrames(frames);
		this.currentFrame = frames[0];
	}
	
	public Animation(ArrayList<KeyFrame> frames){
		this.frames = frames;
		this.numFrames = frames.size();
		this.currentFrame = frames.get(0);
	}
	
	public int getCurrentFrame() {
		return currentFrameIndex;
	}

	public void addFrame(KeyFrame frame) {
		if(!frames.contains(frame)){
			frames.add(frame);
			numFrames++;
		}
	}

	public void setFrames(KeyFrame[] frames) {
		this.frames.clear();
		this.numFrames = frames.length;
		
		for (int i = 0; i < numFrames; i++) {
			this.frames.add(frames[i]);
		}
	}

	public void play() {
		isPlaying = true;
		currentFrameName = null;
		loop = false;
	}

	public void play(String name) {
		currentFrameIndex = 0;
		currentFrameName = name;

		for (int i = 0; i < numFrames; i++) {
			if (frames.get(i).getName().equals(name))
			{
				loopStartIndex = currentFrameIndex = i;
				break;
			}
		}
		
		isPlaying = true;
	}
	
	public void play(String name, boolean loop) {
		this.loop = loop;
		play(name);
	}

	public void stop() {
		isPlaying = false;
		currentFrameIndex = 0;
	}

	public void pause() {
		isPlaying = false;
	}
	
	public float getFps() {
		return fps;
	}

	public void setFps(float fps) {
		this.fps = fps;
	}
	
	public void update() {		
		if (!isPlaying)	return;
		Step.log("Aniamtion-更新动画");

		if(currentFrameName != null && !currentFrameName.equals(currentFrame.getName()))
		{
			if(!loop)
				stop();
			else
				currentFrameIndex = loopStartIndex;
			return;
		}
		
		interpolation += fps * Step.renderer.getDeltaTime();	
		
		if (interpolation > 1) {
			interpolation = 0;
			currentFrameIndex++;

			if (currentFrameIndex >= numFrames)	currentFrameIndex = 0;
			
			currentFrame = frames.get(currentFrameIndex);
		}
	}
}
